package mainpkg

import (
    "appengine"
    "appengine/datastore"
//    "fmt"
    "os"
)




type GroupAddress struct {
	Name string
	Addresses []string
}
type Group struct {
	Name string
	Level int
	Subgroups []Group
}


func getGroups(c appengine.Context, name *string) (groups []Group, err os.Error) {
	c.Debugf( "get-groups.Name:%v", *name)

    q := datastore.NewQuery("Group").
    		Filter( "Level = ", 0).
        	Order("-Name")

    for t := q.Run(c); ; {
	    var group Group
        _, err := t.Next(&group)
        if err == datastore.Done {
			c.Debugf( "get-groups.Done")
			break
        }
        if err != nil {
			c.Debugf( "get-groups.err", err)
			return
        }
		c.Debugf( "get-groups.adding %v", group.Name)
        groups = append( groups, group)
    }
    return
} 
 
// http://localhost:8080/processJSON?cmd={%22QueryGroup%22:%22grumo-test%22}
func getAddresses(c appengine.Context, name *string) (addresses *GroupAddress, err os.Error) {
	c.Debugf( "get-group.Name:%v", *name)
    k := datastore.NewKey("GroupAddress", *name, 0, nil)
    addresses = new(GroupAddress)
    if err = datastore.Get(c, k, addresses); err != nil {
        return nil, err
    }
    return
} 
 

func setAddresses(c appengine.Context, addresses *GroupAddress) (err os.Error) {
	c.Debugf( "set-group.Name:%v", *addresses)
    k := datastore.NewKey("GroupAddress", addresses.Name, 0, nil)
    if _, err = datastore.Put(c, k, addresses); err != nil {
        return err
    }

    group := new(Group)
    group.Name = addresses.Name
    group.Level = 0
    k = datastore.NewKey("Group", group.Name, 0, nil)
    if _, err = datastore.Put(c, k, group); err != nil {
        return err
    }
    return nil
} 
 


